package grapid.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie操作类
 * 
 * @author grapid
 * @version 2.0
 * 
 */
public class GCookies {

	/**
	 * 设置cookies
	 * 
	 * @param response
	 * @param name
	 *            cookie名
	 * @param value
	 *            cookie值
	 * @param domain
	 *            域
	 * @param maxAge
	 *            null 或 -1 代表浏览器进程
	 */
	public static boolean setCookie(HttpServletResponse response, String name, String value, String domain,
			String path, Integer maxAge) {
		if (name == null || name.equals(""))
			return false;
		Cookie cookie = new Cookie(name, value == null ? "" : value);
		if (maxAge != null)
			cookie.setMaxAge(maxAge);
		if (domain != null)
			cookie.setDomain(domain);
		if (path != null)
			cookie.setPath(path);
		else
			cookie.setPath("/");
		response.addCookie(cookie);
		return true;
	}

	/**
	 * 获取cookies
	 * 
	 * @param request
	 * @param name
	 *            cookie名
	 * @return 返回Cookie
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		if (name == null || name.equals(""))
			return null;
		Cookie cookies[] = request.getCookies();
		if (cookies == null)
			return null;
		Cookie cookie = null;
		for (int i = 0; i < cookies.length; i++) {
			if (name.equals(cookies[i].getName())) {
				cookie = cookies[i];
				break;
			}
		}
		return cookie;
	}

	/**
	 * 取cookies值
	 * 
	 * @param request
	 * @param name
	 *            cookie名
	 * @return 返回Cookie值
	 */
	public static String getCookieVal(HttpServletRequest request, String name) {
		Cookie cookie = getCookie(request, name);
		return cookie != null ? cookie.getValue() : null;
	}
}
